package com.example.ref.select;

import java.util.ArrayList;
import java.util.List;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;

import com.example.ref.AbstractWhere;
import com.example.ref.From;
import com.example.ref.RSQLiteDatabaseHelper;


public class Where<T> extends AbstractWhere<T>
{
	List<OrderBy> orderBy;

	public Where(From<T> statement, String field, int operator, Object value)
			throws Exception {
		super(statement, field, operator, value);
		if(statement.orderBy!=null)
			for (OrderBy oby : statement.orderBy) {
				addOrderBy(oby.field, oby.orientation);
			}
	}
	public Where<T> and(String field, int operator, Object value) throws Exception {
		super._and(field, operator, value);
		return this;
	}
	public Where<T> or(String field, int operator, Object value) throws Exception {
		super._or(field, operator, value);
		return this;
	}
	public  Where<T> addOrderBy(String field, String orientation) throws Exception
	{
		RSQLiteDatabaseHelper.throwIfFieldDoesntExists(fields,field);

		if(orderBy==null)
			orderBy= new ArrayList<Where.OrderBy>();

		orderBy.add(new OrderBy(field, orientation));
		return this;
	}

	@Override
	public List<T> execute(Context context) throws Exception {
		return RSQLiteDatabaseHelper.select(null,statement.getInnerClass(), context,builder.toString(),orderBy,((From<T>)statement).getSelect().limit);
	}

	@Override
	public List<T> execute(SQLiteDatabase database, Context context)
			throws Exception {
		return RSQLiteDatabaseHelper.select(database,statement.getInnerClass(), context,builder.toString(),orderBy,((From<T>)statement).getSelect().limit);
	}
	public int count(Context context)
	{	

		return RSQLiteDatabaseHelper.count(statement.getInnerClass(),builder,context);

	}
	/**
	 * Class that manages the order list of a select
	 * @author Giuseppe.Longordo
	 *
	 */
	public static class OrderBy
	{
		public static final String ASCENDENT= "ASC";
		public static final String DESCENDENT= "DESC";

		public OrderBy(String field, String orientation)
		{
			this.field=field;
			this.orientation=orientation;
		}

		public String field;
		public String orientation;

		@Override
		public String toString() {
			return "[".concat(field).concat("] ").concat(orientation).concat(" ");
		}
	}

}